import $$ from 'cmn-utils';
import { routerRedux } from 'dva/router'
import modelEnhance from '@/utils/modelEnhance';
import menus from './menus';

export default modelEnhance({
  namespace: 'global',

  state: {
    menu: [],
    flatMenu: [],
  },

  effects: {
    *getMenu({ payload }, { call, put }) {
      const isToken = yield call(currentUser, payload);
      if ( !isToken ) {
        yield put(routerRedux.replace('/sign/login'));
        return;
      }
      const { data } = isToken
      $$.setStore('user', data);

      const {data: menu} = yield call(getMenu, {idList: data.roleBoList.map(item=> item.id)});

      const loopMenu = (menu, pitem = {}) => {
        menu.forEach(item => {
          if (pitem.path) {
            item.parentPath = pitem.parentPath ? pitem.parentPath.concat(pitem.path) : [pitem.path];
          }
          if (item.children && item.children.length) {
            loopMenu(item.children, item);
          }
        });
      }

      const checkAuth = (item) =>{
        if(item.hasAuth) return true;
        let key = false;
        if(item.children && item.children.length){
          item.children.forEach(child => {
            if (checkAuth(child)) {
              key = true;
            }
          })
        }
        // return item;
        return key;
      }

      const checkMenuAuth = (l_menu = {}) =>{
        let temp_menu = [];
        l_menu.forEach((item, k)=> {
          if(checkAuth(item)){
            temp_menu.push(item);
          };
          if(item.children && item.children.length){
              item.children = checkMenuAuth(item.children);
          }
        });

        return temp_menu

      };

      let n_menu = checkMenuAuth(menu);
      loopMenu(n_menu);
      // loopMenu(menus['admin']);

      yield put({
        type: 'getMenuSuccess',
        // payload: menus['admin'].concat(menu),
        payload: n_menu,
      });
    },
  },

  reducers: {
    getMenuSuccess(state, { payload }) {
      return {
        ...state,
        menu: payload,
        flatMenu: getFlatMenu(payload),
      };
    }
  },
});

export function getFlatMenu(menus) {
  let menu = [];
  menus.forEach(item => {
    if (item.children) {
      menu = menu.concat(getFlatMenu(item.children));
    }
    menu.push(item);
  });
  return menu;
}

export async function currentUser(payload) {
  return $$.post('/currentUser', payload);
}

export async function getMenu(payload) {
  return $$.post('/api/authManage/menu/menuTree/byRoleIds', payload);
}
